package com.xnyzc.lhy.nio.netty;

import com.alibaba.fastjson.JSON;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.constant.MethodConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.entity.Qd;
import com.xnyzc.lhy.common.entity.netty.NettyDriverOrderInfo;
import com.xnyzc.lhy.common.penum.order.EDiDiOrderStatus;
import com.xnyzc.lhy.common.penum.order.EOrderStatus;
import com.xnyzc.lhy.common.penum.vehicle.ECallVehType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.DateUtil;
import com.xnyzc.lhy.common.util.NumberToChn;
import com.xnyzc.lhy.nio.feign.amap.IAmapService;
import com.xnyzc.lhy.nio.feign.netty.FeignNettyService;
import com.xnyzc.lhy.order.entity.gps.OaCUserGps;
import com.xnyzc.lhy.order.entity.gps.OaDVehicleGps;
import com.xnyzc.lhy.order.entity.order.OaCOrder;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;


/**
 * @Author: huxuekuo
 * @Date: 2019-09-02 23:48
 * @Description:
 */
@Component
@Slf4j
public class NettyPushCommon {

    @Autowired
    private RedisCommon redisCommon;

    @Autowired
    private FeignNettyService feignNettyService;

    @Autowired
    private IAmapService amapService;

    /**
     * 根据orderNo获取订单实体类
     *
     * @param orderNo
     * @return
     */
    public Qd isTrue(String orderNo) {
        Qd qd = Qd.create();
        OaCOrder oaCOrder = null;
        String orderJson = redisCommon.getStr(RedisPrefixConstant.ORDER_OA_D_ORDER + orderNo);
        if (CheckUtil.strIsNotEmpty(orderJson)) {
            oaCOrder = JSON.parseObject(orderJson, OaCOrder.class);
            qd.add("oaCOrder", oaCOrder);
            //如果是到达预约地点之前的返回开始地点
            if (oaCOrder.getOrderStatus() == 4 || oaCOrder.getOrderStatus() == 3) {
                qd.add("endLng", oaCOrder.getStartLng());
                qd.add("endLat", oaCOrder.getStartLat());
                //到达预约地点之后放回结束地点
            } else if (oaCOrder.getOrderStatus() == 5 || oaCOrder.getOrderStatus() == 6 || oaCOrder.getOrderStatus() == 13) {
                qd.add("endLng", oaCOrder.getEndLng());
                qd.add("endLat", oaCOrder.getEndLat());
            } else {
                return qd;
            }
        } else {
            return qd;
        }
        return qd;
    }

    /**
     * 获取用户定位给司机
     *
     * @param qd
     * @param ctx
     * @param oaDVehicleGps
     */
    public void getUserMessageSendDriver(Qd qd, ChannelHandlerContext ctx, OaDVehicleGps oaDVehicleGps, NettyDriverOrderInfo driverOrderInfo) {
        if (CheckUtil.objIsEmpty(qd)) {
            log.info("sendDriverMsg 获取Map信息为空");
            return;
        }
        if (!qd.containsKey("oaCOrder")) {
            log.info("sendDriverMsg 获取Map中不保存订单");
            return;
        }
        OaCOrder oaCOrder = (OaCOrder) qd.get("oaCOrder");
        log.info("sendDriverMsg 当前获取到的订单: " + oaCOrder.getOrderNo() + ", 当前订单状态: " + oaCOrder.getOrderStatus());
        log.info("sendDriverMsg ------------为司机准备订单信息(Start)------------");
        OaCUserGps userGps = JSON.parseObject(redisCommon.getStr(RedisPrefixConstant.GPS_USER_KEYP_REFIX + oaCOrder.getUserId()), OaCUserGps.class);
        driverOrderInfo.setDistance("时间 暂无");
        driverOrderInfo.setDistanceTime("");
        driverOrderInfo.setOrderStatus(oaCOrder.getOrderStatus());
        driverOrderInfo.setOrderNo(oaCOrder.getOrderNo());
        //获取 用户定位
        if (CheckUtil.objIsNotEmpty(userGps)) {
            driverOrderInfo.setUserLng(userGps.getLng());
            driverOrderInfo.setUserLat(userGps.getLat());
        }
        if (CheckUtil.objIsNotEmpty(oaCOrder)) {
            driverOrderInfo.setTotalFee(String.valueOf(oaCOrder.getDrawFee()));
            driverOrderInfo.setEndAddress(oaCOrder.getEndAddress());
            driverOrderInfo.setStartAddress(oaCOrder.getStartAddress());
            driverOrderInfo.setStartLat(oaCOrder.getStartLat());
            driverOrderInfo.setStartLng(oaCOrder.getStartLng());
            driverOrderInfo.setEndLat(oaCOrder.getEndLat());
            driverOrderInfo.setEndLng(oaCOrder.getEndLng());
            driverOrderInfo.setCallVehType(MessageConstant.ORDER_TYPE_ONE);
            driverOrderInfo.setOrderType(ECallVehType.finaByValue(oaCOrder.getOrderType()));
            driverOrderInfo.setGpsId(oaCOrder.getGpsId());
            String phone = oaCOrder.getPassengerPhone();
            driverOrderInfo.setPhone(phone);
            driverOrderInfo.setTailNumber(MessageConstant.TAILNUMBER + oaCOrder.getPassengerPhoneSuffix());
            driverOrderInfo.setDistance(oaCOrder.getMilageDistance().toString());
            driverOrderInfo.setDistanceTime(oaCOrder.getDurationTime().toString());
            try {
                driverOrderInfo.setTime(CheckUtil.objIsEmpty(oaCOrder.getAppointment()) ? DateUtil.getChineseDate(null) : DateUtil.getChineseDate(oaCOrder.getAppointment()));
            } catch (ParseException e) {
                log.error("sendDriverMsg 获取时间转换失败!");
            }
            //设置猎鹰获取历史轨迹需要的ID
            driverOrderInfo.setGpsId(oaCOrder.getGpsId());
            driverOrderInfo.setTid(oaCOrder.getTid());
            driverOrderInfo.setServiceId(oaCOrder.getServiceId());
        }
        String jsonString = JSON.toJSONString(driverOrderInfo);
        log.info("sendDriverMsg ------------为司机准备订单信息结束,并且开始发送给司机,当前发送的信息为: {}------------", jsonString);
        NettyServerService.sendMsgToClient(ctx, NettyMsg.setJsonMsg(MethodConstant.DRIVER_GET_ORDER_MESSAGE, jsonString));
    }

    /**
     * 更新根据订单号获取订单信息,园通道返回
     * 如果上传orderNo为空,则只能查询当前是否有订单
     *
     * @param ctx
     * @param orderNo
     * @param driverId
     */
    public void sendDriverMsg(ChannelHandlerContext ctx, String orderNo, String driverId, OaDVehicleGps oaDVehicleGps) {
        log.info("sendDriverMsg 司机开始获取订单信息,当前上传的订单号为: {}" + orderNo);
        log.info("sendDriverMsg ------------司机开始获取订单信息(Start)------------");
        String orderVeh = RedisPrefixConstant.ORDER_VEH + driverId;
        redisCommon.remove(orderVeh);
        Qd qd = isTrue(orderNo);
        //在进行中的订单
        if (CheckUtil.objIsNotEmpty(qd) && qd.containsKey("oaCOrder")) {
            Object obj = qd.get("oaCOrder");
            if (CheckUtil.objIsEmpty(obj)) {
                log.info("sendDriverMsg 获取到的订单实体类为空!");
                return;
            }
            //如果有订单全程发送用户轨迹以及费用信息
            NettyDriverOrderInfo driverOrderInfo = new NettyDriverOrderInfo();
            getUserMessageSendDriver(qd, ctx, oaDVehicleGps, driverOrderInfo);
        }
    }

    /**
     * 回传司机上传定位信息
     *
     * @param ctx
     */
    public void sendDriverLocationMsg(ChannelHandlerContext ctx) {
        //上传司机定位时则检查有无预约单-任恒荣改
//        long endTime = System.currentTimeMillis() + Configuration.DELAY_ROB_BOOKING;
//        long count = redisCommon.getZSetCount(RedisPrefixConstant.ORDER_TC_HALL, 0L, endTime);
//        if (count > 0) {
//            NettyServerService.sendMsgToClient(ctx, NettyMsg.setJsonMsg(MethodConstant.GDLOC, "" + EOrderStatus.bookingOrder.getValue()));
//        } else {
//            NettyServerService.sendMsgToClient(ctx, NettyMsg.setJsonMsg(MethodConstant.GDLOC, "0"));
//        }
        NettyServerService.sendMsgToClient(ctx, NettyMsg.setJsonMsg(MethodConstant.GDLOC, "{}"));
    }
}
